﻿using BZOrderPrint.BLL.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BZOrderPrint.DAL;
using BZOrderPrint.DAL.Entity;
using BZOrderPrint.Model;
using System.Linq.Expressions;
using System.Collections;
using System.Diagnostics;
using System.IO;
using static BZOrderPrint.DAL.AppEnum;
using BZOrderPrint.BLL.Model;
using BZOrderPrint.PDF;
using System.Data.Entity;

namespace BZOrderPrint
{
    public partial class OrderForm : Form
    {
        private BZContext context;

        public OrderForm()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            context = new BZContext(ConfigHelper.ConnString);
        }

        private void OrderForm_Load(object sender, EventArgs e)
        {
            StoreInit();
            OrderStatusInit();
            GroupTypeInit();
            PayTypeInit();
            GridViewInit(GetOrderList(true, 1));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i = 1;
            if (!int.TryParse(pageIndex.Text, out i))
                MessageBox.Show("页码错误");

            GridViewInit(GetOrderList(false, i));
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            int i;
            if (!int.TryParse(pageIndex.Text, out i))
                MessageBox.Show("页码错误");
            --i;
            if (i == 0)
                return;

            GridViewInit(GetOrderList(false, i));
            pageIndex.Text = i.ToString();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int i;
            if (!int.TryParse(pageIndex.Text, out i))
                MessageBox.Show("页码错误");

            GridViewInit(GetOrderList(false, ++i));
            pageIndex.Text = i.ToString();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
        }

        private PageOrderModel GetOrderList(bool isInit, int PageIndex)
        {
            PageOrderModel model = new PageOrderModel();
            IQueryable<BzOrderEntity> data;
            if (isInit)
            {
                data = context.bzOrderEntities.OrderByDescending(x => x.CreateTime).Skip(0).Take(30);
            }
            else
            {
                Expression<Func<BzOrderEntity, bool>> predicate = x => true;

                if (!string.IsNullOrEmpty(tb_order_code.Text))
                    predicate = predicate.And(x => x.OrderCode.Contains(tb_order_code.Text.Trim()));

                if (cBoxStore.SelectedIndex != -1 && cBoxStore.SelectedValue.ToString() != "-1")
                {
                    predicate = predicate.And(x => x.OrderShopId == (int)cBoxStore.SelectedValue);
                }
                if (cb_group_type.SelectedIndex != -1 && cb_group_type.SelectedValue.ToString() != "-1")
                {
                    predicate = predicate.And(x => x.IsGroup == (int)cb_group_type.SelectedValue);
                }
                if (cb_order_status.SelectedIndex != -1 && cb_order_status.SelectedValue.ToString() != "-1")
                {
                    predicate = predicate.And(x => x.OrderStatus == (int)cb_order_status.SelectedValue);
                }
                if (cb_paytype.SelectedIndex != -1 && cb_paytype.SelectedValue.ToString() != "-1")
                {
                    predicate = predicate.And(x => x.OrderStatus == (int)cb_paytype.SelectedValue);
                }

                if (!string.IsNullOrEmpty(tb_member_code.Text))
                    predicate = predicate.And(x => x.MemberNumber.Contains(tb_member_code.Text.Trim()));

                if (checkBox2.Checked)
                {
                    var startDate = dateTimePicker1.Value.Date;
                    var endDate = dateTimePicker1.Value.Date.AddDays(1);
                    predicate = predicate.And(x => x.OrderDateTime > startDate && x.OrderDateTime < endDate);
                }

                data = context.bzOrderEntities.Where(predicate).OrderByDescending(x => x.CreateTime);
            }

            if (data.Count() > 0)
            {
                model.TotalRows = data.Count();
                model.TotalPage = data.Count() / 30 + 1;
                model.PageIndex = PageIndex;
                model.PageSize = 30;
                model.orderEntities = data.Skip((PageIndex - 1) * 30).Take(30).OrderByDescending(x => x.CreateTime).ToList();
            }
            else
            {
                model.TotalRows = 0;
                model.TotalPage = 0;
                model.PageIndex = PageIndex;
                model.PageSize = 30;
            }
            return model;
        }

        private void StoreInit()
        {
            var list = context.bzShopEntities.ToList();
            if (list.Count > 0)
            {
                var listData = list.Select(x => new DictionaryEntry { Value = x.Id, Key = x.ShopName }).ToList();
                var indexItem = new DictionaryEntry { Value = "-1", Key = "全部" };
                listData.Add(indexItem);
                cBoxStore.DataSource = listData;
                cBoxStore.DisplayMember = "Key";
                cBoxStore.ValueMember = "Value";
                cBoxStore.SelectedItem = indexItem;
            }
        }

        private void GroupTypeInit()
        {
            var list = Enum.GetValues(typeof(GroupType));
            List<DictionaryEntry> dataList = new List<DictionaryEntry>();
            foreach (var item in list)
            {
                DictionaryEntry info = new DictionaryEntry { Value = (int)(GroupType)item, Key = EnumHelper.GetDescription((GroupType)item) };
                dataList.Add(info);
            }
            var indexItem = new DictionaryEntry { Value = "-1", Key = "全部" };
            dataList.Add(indexItem);
            cb_group_type.DataSource = dataList;
            cb_group_type.DisplayMember = "Key";
            cb_group_type.ValueMember = "Value";
            cb_group_type.SelectedItem = indexItem;
        }

        private void OrderStatusInit()
        {
            var list = Enum.GetValues(typeof(OrderStatus));
            List<DictionaryEntry> dataList = new List<DictionaryEntry>();
            foreach (var item in list)
            {
                DictionaryEntry info = new DictionaryEntry { Value = (int)(OrderStatus)item, Key = EnumHelper.GetDescription((OrderStatus)item) };
                dataList.Add(info);
            }
            var indexItem = new DictionaryEntry { Value = "-1", Key = "全部" };
            dataList.Add(indexItem);
            cb_order_status.DataSource = dataList;
            cb_order_status.DisplayMember = "Key";
            cb_order_status.ValueMember = "Value";
            cb_order_status.SelectedItem = indexItem;
        }

        private void PayTypeInit()
        {
            var list = Enum.GetValues(typeof(PayType));
            List<DictionaryEntry> dataList = new List<DictionaryEntry>();
            foreach (var item in list)
            {
                DictionaryEntry info = new DictionaryEntry { Value = (int)(PayType)item, Key = EnumHelper.GetDescription((PayType)item) };
                dataList.Add(info);
            }
            var indexItem = new DictionaryEntry { Value = "-1", Key = "全部" };
            dataList.Add(indexItem);
            cb_paytype.DataSource = dataList;
            cb_paytype.DisplayMember = "Key";
            cb_paytype.ValueMember = "Value";
            cb_paytype.SelectedItem = indexItem;
        }

        private void GridViewInit(PageOrderModel model)
        {
            var data = new DataTable();
            dataGridView1.Columns.Clear();
            var dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "ID",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);

            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "orderType",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "orderStatus",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "payType",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "shipMethod",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单号",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "批发开单号",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "店铺名称",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "日期",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单类型",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单来源",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单状态",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单金额",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "配送方式",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "支付方式",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "会员编号",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "会员名称",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "联系电话",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "配送地址",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "备注",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "OrderShopId",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "IsGroup",
                DefaultValue = "",
                ReadOnly = true
            };
            data.Columns.Add(dc);
            if (model.orderEntities.Count > 0)
            {
                foreach (var item in model.orderEntities)
                {
                    var dataRow = data.NewRow();
                    dataRow["ID"] = item.Id;
                    dataRow["orderType"] = item.OrderType;
                    dataRow["orderStatus"] = item.OrderStatus;
                    dataRow["payType"] = item.PayType;
                    dataRow["shipMethod"] = item.ShipMethod;
                    dataRow["订单号"] = item.OrderCode;
                    var wholeOrder = context.bzYbLineEntities.FirstOrDefault(x => x.BzOrderId == item.Id);
                    dataRow["批发开单号"] = wholeOrder != null ? wholeOrder.BzWhloeOrderCode : "";
                    dataRow["店铺名称"] = item.OrderShopName;
                    dataRow["日期"] = item.OrderDateTime?.ToString("yyyy-MM-dd HH:mm:ss");
                    dataRow["订单类型"] = BLL.Helper.EnumHelper.GetDescription((AppEnum.GroupType)item.IsGroup);
                    dataRow["订单来源"] = BLL.Helper.EnumHelper.GetDescription((AppEnum.OrderType)item.OrderType);
                    dataRow["订单状态"] = BLL.Helper.EnumHelper.GetDescription((AppEnum.OrderStatus)item.OrderStatus);
                    dataRow["订单金额"] = item.OrderPrice;
                    dataRow["配送方式"] = EnumHelper.GetDescription((AppEnum.ShipMethodType)item.ShipMethod);
                    dataRow["支付方式"] = BLL.Helper.EnumHelper.GetDescription((AppEnum.PayType)item.PayType);
                    dataRow["会员编号"] = item.MemberNumber;
                    dataRow["会员名称"] = item.MemberName;
                    dataRow["联系电话"] = item.Phone;
                    dataRow["配送地址"] = item.Address;
                    dataRow["备注"] = item.Remark;
                    dataRow["OrderShopId"] = item.OrderShopId;
                    dataRow["IsGroup"] = item.IsGroup;
                    data.Rows.Add(dataRow);
                }
                DataGridViewCheckBoxColumn checkColum = new DataGridViewCheckBoxColumn();
                checkColum.HeaderText = "选择";
                checkColum.Name = "IsChecked";
                checkColum.DataPropertyName = "IsChecked";
                checkColum.ReadOnly = false;
                checkColum.TrueValue = true;
                checkColum.FalseValue = false;
                checkColum.Width = 40;
                dataGridView1.Columns.Insert(0, checkColum);
                DataGridViewButtonColumn buttonColum = new DataGridViewButtonColumn();
                buttonColum.Text = "查看";
                buttonColum.Name = "查看";
                buttonColum.ToolTipText = "查看";
                buttonColum.ReadOnly = false;
                buttonColum.Width = 40;
                dataGridView1.Columns.Insert(1, buttonColum);

                dataGridView1.DataSource = data;
                dataGridView1.ReadOnly = false;
                dataGridView1.Columns[0].ReadOnly = false;
                dataGridView1.Columns[1].ReadOnly = false;
                //dataGridView1.Columns[2].Visible = false;
                dataGridView1.Columns[3].Visible = false;
                dataGridView1.Columns[4].Visible = false;
                dataGridView1.Columns[5].Visible = false;
                dataGridView1.Columns[6].Visible = false;
                dataGridView1.Columns[2].Width = 50;
                dataGridView1.Columns[7].Width = 150;
                dataGridView1.Columns[8].Width = 150;
                dataGridView1.Columns[9].Width = 150;
                dataGridView1.Columns[10].Width = 150;
                dataGridView1.Columns[11].Width = 100;
                dataGridView1.Columns[12].Width = 100;
                dataGridView1.Columns[13].Width = 80;
                dataGridView1.Columns[14].Width = 100;
                dataGridView1.Columns[15].Width = 100;
                dataGridView1.Columns[22].Visible = false;
                dataGridView1.Columns[23].Visible = false;
                for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                pagaText.Text = string.Format("共{0}条记录，每页{1}条，共{2}页", model.TotalRows, model.PageSize, model.TotalPage);
                pageIndex.Text = model.PageIndex.ToString();
            }
            else
                pagaText.Text = string.Format("共{0}条记录，每页{1}条，共{2}页", model.TotalRows, model.PageSize, model.TotalPage);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkbox1.Checked == true)
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    this.dataGridView1.Rows[i].Cells[0].Value = true;
                }
            }
            if (checkbox1.Checked == false)
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    this.dataGridView1.Rows[i].Cells[0].Value = false;
                }
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //OrderDetailModel detailModel = new OrderDetailModel();
            //detailModel.order = GetOrder(dataGridView1.Rows[e.RowIndex]);
            //OrderDetailFoim orderDetailFoim = new OrderDetailFoim(detailModel);
            //orderDetailFoim.Show();
        }

        private BzOrderEntity GetOrder(DataGridViewRow data)
        {
            BzOrderEntity entity = new BzOrderEntity();

            entity.Id = int.Parse(data.Cells["ID"].Value.ToString());

            var type = typeof(int);
            entity.OrderCode = data.Cells["订单号"].Value.ToString();
            entity.OrderShopName = data.Cells["店铺名称"].Value.ToString();
            if (data.Cells["日期"].Value != null)
                entity.OrderDateTime = DateTime.Parse(data.Cells["日期"].Value.ToString());

            double price = 0.0d;
            if (data.Cells["订单金额"].Value != null)
                entity.OrderPrice = double.TryParse(data.Cells["订单金额"].Value.ToString(), out price) ? double.Parse(data.Cells["订单金额"].Value.ToString()) : price;

            entity.OrderStatus = int.Parse(data.Cells["orderStatus"].Value.ToString());
            entity.OrderShopId = int.Parse(data.Cells["OrderShopId"].Value.ToString());
            entity.OrderType = int.Parse(data.Cells["orderType"].Value.ToString());
            entity.ShipMethod = int.Parse(data.Cells["shipMethod"].Value.ToString());
            entity.PayType = int.Parse(data.Cells["payType"].Value.ToString());
            entity.MemberNumber = data.Cells["会员编号"].Value?.ToString();
            entity.MemberName = data.Cells["会员名称"].Value?.ToString();
            entity.Phone = data.Cells["联系电话"].Value?.ToString();
            entity.Address = data.Cells["配送地址"].Value?.ToString();
            entity.Remark = data.Cells["备注"].Value?.ToString();
            entity.IsGroup = int.Parse(data.Cells["IsGroup"].Value?.ToString());
            return entity;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (column is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                OrderDetailModel detailModel = new OrderDetailModel();
                detailModel.order = GetOrder(dataGridView1.Rows[e.RowIndex]);
                detailModel.orderItems = context.bzOrderItemEntities.Where(x => x.OrderId == detailModel.order.Id).ToList();
                OrderDetailFoim orderDetailFoim = new OrderDetailFoim(detailModel);
                orderDetailFoim.Show();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<BzOrderEntity> orders = new List<BzOrderEntity>();
            for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                if ((bool)dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                {
                    int Id = int.Parse(dataGridView1.Rows[i].Cells["ID"].Value.ToString());
                    if (context.bzYbLineEntities.Count(x => x.BzOrderId == Id) > 0)
                    {
                        MessageBox.Show("订单" + dataGridView1.Rows[i].Cells["订单号"].Value.ToString() + "，已存在对应的批发开单记录");
                        return;
                    }
                    else
                    {
                        orders.Add(GetOrder(dataGridView1.Rows[i]));
                    }
                }
            }

            if (orders.Count > 0)
            {
                if (orders.Select(x => x.OrderShopId).Distinct().ToList().Count > 1)
                {
                    MessageBox.Show("不能跨店生成批发开单");
                    return;
                }
                if (orders.Select(x => x.IsGroup).Distinct().ToList().Count > 1)
                {
                    MessageBox.Show("只能同一类型订单生成批发开单");
                    return;
                }
                if (orders.Count > 1 && orders.Any(x => x.IsGroup == (int)GroupType.TeamOrder))
                {
                    MessageBox.Show("团购订单只能选择一个生成批发开单");
                    return;
                }
                BzWhloeOrderEntity bzWhloeOrder = new BzWhloeOrderEntity();
                bzWhloeOrder.WhloeOrderCode = orders.FirstOrDefault().OrderShopId + "BZWO" + DateTime.Now.ToString("yyyyMMddhhmmss");
                bzWhloeOrder.BzShopeId = orders.FirstOrDefault().OrderShopId;
                bzWhloeOrder.CreateTime = DateTime.Now;
                bzWhloeOrder.IsGroup = orders.FirstOrDefault().IsGroup;
                context.bzWhloeOrderEntities.Add(bzWhloeOrder);
                var bzyb = orders.Select(x => new BzYbLineEntity { BzOrderId = x.Id, BzWhloeOrderCode = bzWhloeOrder.WhloeOrderCode }).ToArray();
                context.bzYbLineEntities.AddRange(bzyb);
                context.SaveChanges();
                MessageBox.Show("生成完成");
            }
            else
                MessageBox.Show("请选择需要打印的数据");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            List<BzOrderItemEntity> orderItems = new List<BzOrderItemEntity>();
            for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                if ((bool)dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                {
                    int Id = int.Parse(dataGridView1.Rows[i].Cells["ID"].Value.ToString());
                    var items = context.bzOrderItemEntities.Where(x => x.OrderId.Equals(Id)).ToList();
                    if (items.Any())
                    {
                        orderItems.AddRange(items);
                    }
                    //OrderDetailModel detailModel = new OrderDetailModel();
                    //detailModel.order = GetOrder(dataGridView1.Rows[i]);
                    //detailModel.orderItems = context.bzOrderItemEntities.Where(x => x.OrderId == detailModel.order.Id).ToList();
                    //detailModels.Add(detailModel);
                }
            }

            if (orderItems.Count > 0)
            {
                var data = new DataTable();
                var dc = new DataColumn()
                {
                    DataType = Type.GetType("System.String"),
                    ColumnName = "商品名称",
                    DefaultValue = "",
                    ReadOnly = true
                };
                data.Columns.Add(dc);
                dc = new DataColumn()
                {
                    DataType = Type.GetType("System.String"),
                    ColumnName = "条码（必填）",
                    DefaultValue = "",
                    ReadOnly = true
                };
                data.Columns.Add(dc);
                dc = new DataColumn()
                {
                    DataType = Type.GetType("System.String"),
                    ColumnName = "售价",
                    DefaultValue = "",
                    ReadOnly = true
                };
                data.Columns.Add(dc);
                dc = new DataColumn()
                {
                    DataType = Type.GetType("System.String"),
                    ColumnName = "数量",
                    DefaultValue = "",
                    ReadOnly = true
                };
                data.Columns.Add(dc);
                dc = new DataColumn()
                {
                    DataType = Type.GetType("System.String"),
                    ColumnName = "赠送量",
                    DefaultValue = "",
                    ReadOnly = true
                };
                data.Columns.Add(dc);
                var orderItemCodes = orderItems.Select(x => x.OrderItemCode).Distinct().ToList();
                foreach (var orderItemCode in orderItemCodes)
                {
                    var orderItem = orderItems.FirstOrDefault(x => x.OrderItemCode.Equals(orderItemCode));
                    var dataRow = data.NewRow();
                    dataRow["商品名称"] = orderItem?.OrderItem?.Split('（').FirstOrDefault();
                    dataRow["条码（必填）"] = orderItem?.OrderItemCode;
                    dataRow["售价"] = orderItem?.Price;
                    dataRow["数量"] = orderItems.Where(x => x.OrderItemCode.Equals(orderItemCode)).Sum(x => x.Quantity);
                    dataRow["赠送量"] = "";
                    data.Rows.Add(dataRow);
                }

                var fileName = $"批发单开单-{DateTime.Now:yyyyMMddHHmm}.xlsx";
                var directory = Environment.CurrentDirectory + @"\tempfile";
                if (!Directory.Exists(directory))//如果不存
                {
                    Directory.CreateDirectory(directory);
                }
                ExcelHelper.DataTableToExcel(data, directory + @"\" + fileName, true);
                Process.Start("Explorer", "/select," + directory + @"\" + fileName);
                MessageBox.Show("导出完成");
            }
            else
                MessageBox.Show("请选择需要导出的数据");
        }
    }
}